package com.hk.web.controller.financialPlanner;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.base.ResponseBase;
import com.hk.commons.CardStatusCode;
import com.hk.commons.ConstantOrderStatus;
import com.hk.commons.DateUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.view.OrderView;
import com.hk.commons.entity.view.PaymentView;
import com.hk.commons.entity.view.ReservView;
import com.hk.service.sys.ISysUser;
import com.hk.service.view.IOrderView;
import com.hk.service.view.IPaymentView;
import com.hk.service.view.IReservView;

@Controller
@RequestMapping(value = "financial/mainPageMenuList")
public class MainPageGetMenuInfos {
	private Logger logger = LoggerFactory.getLogger(MainPageGetMenuInfos.class);
	@Autowired
	private IOrderView orderViewService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private IPaymentView paymentViewService;

	@Autowired
	private IReservView reservViewService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 我的佣金=产品购买金额*产品佣金比例*产品期限（天数）/365
	 */
	@ResponseBody
	@RequestMapping(value = "/getCommision", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<Map<String, Object>> getCommision(
			@RequestParam String recommendCode, String pageNum,
			String searchType) {
		logger.info("查询我的佣金recommendCode={},pageNum={},searchType={}",
				recommendCode, pageNum, searchType);
		ResponseBase<Map<String, Object>> resultBase = new ResponseBase<Map<String, Object>>();
		try {
			if (!("1".equals(searchType) || "0".equals(searchType))) {
				resultBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
			}
			int pageSize = 20;
			Map<String, Object> resultMap = new HashMap<String, Object>();
			List<Map<String, String>> resultMapList = new ArrayList<Map<String, String>>();
			BigDecimal allCommission = new BigDecimal("0");

			// 查询总佣金金额
			allCommission = orderViewService.getTotalCommByFinPhone(
					recommendCode, ConstantOrderStatus.COMMISSION_ALL);
			BigDecimal onWayCommission = orderViewService
					.getTotalCommByFinPhone(recommendCode,
							ConstantOrderStatus.COMMISSION_ONWAY);
			BigDecimal payedCommission = orderViewService
					.getTotalCommByFinPhone(recommendCode,
							ConstantOrderStatus.COMMISSION_PAYED);
			if ("1".equals(searchType)) {// 我的佣金部分需要返回分页List
				HqlFilter hqlFilter = new HqlFilter();
				hqlFilter.addEQFilter("recommendCode", recommendCode);
				List<OrderView> orderViewList = orderViewService.findByFilter(
						hqlFilter, Integer.parseInt(pageNum), pageSize);
				if (orderViewList.size() > 0) {
					for (OrderView view : orderViewList) {
						Map<String, String> map = new HashMap<String, String>();
						String productName = view.getProductName();
						String orderDate = view.getOrderCreatedOn() == null ? ""
								: DateUtil.transferLongToDate("yyyy-MM-dd",
										view.getOrderCreatedOn());
						BigDecimal commission = view.getCommissionAmount() == null ? new BigDecimal(
								0) : view.getCommissionAmount();
						map.put("date", orderDate);
						map.put("commission", String.valueOf(commission) + "元");
						map.put("productName", productName);
						resultMapList.add(map);
					}
				}
				resultMap.put("commissionList", resultMapList);
			}

			resultMap.put(
					"allCommission",
					""
							+ getBigDecimal(allCommission).setScale(2,
									BigDecimal.ROUND_DOWN) + "元");// 直接截短为两位，没有四舍五入。
			resultMap.put(
					"onWayCommission",
					""
							+ getBigDecimal(onWayCommission).setScale(2,
									BigDecimal.ROUND_DOWN) + "元");// 直接截短为两位，没有四舍五入。
			resultMap.put(
					"payedCommission",
					""
							+ getBigDecimal(payedCommission).setScale(2,
									BigDecimal.ROUND_DOWN) + "元");// 直接截短为两位，没有四舍五入。
			resultBase.setResultCode(ResultCode.SUCC.getCode());
			resultBase.setResult(resultMap);
			resultBase.setSize(resultMapList.size());
		} catch (Exception e) {
			logger.error("获取佣金异常！", e);
			resultBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
		}

		return resultBase;

	}

	private BigDecimal getBigDecimal(BigDecimal old) {
		return old == null ? new BigDecimal(0) : old;
	}

	/************************************** todo :统计包括理财师本身 *********************************************/

	@ResponseBody
	@RequestMapping(value = "/getMainPageCounts", method = RequestMethod.GET)
	public ResponseBase<Map<String, String>> getMainPageCounts(
			@RequestParam String recommendCode, String reserv) {
		logger.info("getMainPageCounts入参--recommendCode={}", recommendCode);
		ResponseBase<Map<String, String>> resultBase = new ResponseBase<Map<String, String>>();
		Map<String, String> resultMap = new HashMap<String, String>();
		String getSumCardsSql = "select count(distinct t.userId) from t_payment t where t.userId in (select Id from SysUser where recommendCode="
				+ recommendCode + ")";
		String getSumOrderAmountSql = "select sum(successAmount) from t_order_info where userId in (select Id from SysUser where recommendCode="
				+ recommendCode + ")";

		String getSumOrdersSql = "select count(*) from t_order_info where userId in (select Id from SysUser where recommendCode="
				+ recommendCode + ")";
		String getSumCustomersSql = "select count(distinct u.Id ) from SysUser u where u.recommendCode="
				+ recommendCode;
		String getSumAppointmentsSql = "select count(*) from t_reservation_info where userId in(select Id from SysUser where recommendCode="
				+ recommendCode + ")";
		try {
			BigDecimal sumOrderAmount = jdbcTemplate.queryForObject(
					getSumOrderAmountSql, null, BigDecimal.class);
			int sumCardsCount = jdbcTemplate.queryForObject(getSumCardsSql,
					null, Integer.class);
			int sumOrdersCount = jdbcTemplate.queryForObject(getSumOrdersSql,
					null, Integer.class);
			int sumCustomersCount = jdbcTemplate.queryForObject(
					getSumCustomersSql, null, Integer.class);
			int sumAppointmentsCount = jdbcTemplate.queryForObject(
					getSumAppointmentsSql, null, Integer.class);
			resultMap.put("sumOrderAmount", "" + getBigDecimal(sumOrderAmount));
			resultMap.put("sumCardsCount", "" + sumCardsCount);
			resultMap.put("sumOrdersCount", "" + sumOrdersCount);
			resultMap.put("sumCustomersCount", "" + sumCustomersCount);
			resultMap.put("sumAppointmentsCount", "" + sumAppointmentsCount);
			resultBase.setResult(resultMap);
			resultBase.setResultCode(ResultCode.SUCC.getCode());
		} catch (Exception e) {
			logger.info("查询首页统计总数异常！recommendCode={}", recommendCode);
			logger.error("查询首页统计总数异常！", e);
			resultBase.setResultCode(ResultCode.FAILED.getCode());
			resultBase.setMsg(ResultCode.FAILED.getMsg());
		}
		return resultBase;
	}

	@ResponseBody
	@RequestMapping(value = "/getCardsList", method = RequestMethod.GET)
	public ResponseBase<List<Map<String, String>>> getCardsList(
			@RequestParam String recommendCode, String curPage,
			String searchName) {
		logger.info(
				"getCardsList入参--recommendCode={},curPage={},searchName={}",
				recommendCode, curPage, searchName);
		int pageSize = 20;
		ResponseBase<List<Map<String, String>>> resultBase = new ResponseBase<List<Map<String, String>>>();
		try {
			List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
			HqlFilter paymentilter = new HqlFilter();
			if (StringHelper.isNotEmpty(searchName)) {
				paymentilter.addLKFilter("realName", searchName);
			}
			paymentilter.addEQFilter("recommendCode", recommendCode);
			paymentilter.addSort("createCts");
			paymentilter.addOrder("desc");
			List<PaymentView> paymentViewList = paymentViewService
					.findByFilter(paymentilter, Integer.parseInt(curPage),
							pageSize);
			if (paymentViewList.size() > 0) {
				for (PaymentView pv : paymentViewList) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("bindDate",
							pv.getCreateCts() == null ? "" : DateUtil
									.transferLongToDate("yyyy-MM-dd",
											pv.getCreateCts()));
					map.put("realName",
							pv.getRealName() == null ? "" : pv.getRealName());
					map.put("phone", pv.getPhone() == null ? "" : pv.getPhone());
					map.put("encryPhone", pv.getEncryptPhone());
					resultList.add(map);
				}
			}
			resultBase.setResult(resultList);
			resultBase.setResultCode(ResultCode.SUCC.getCode());
			resultBase.setSize(resultList.size());
		} catch (Exception e) {
			logger.error("理财师：获取绑卡列表异常！", e);
			logger.info("理财师：获取绑卡列表异常！recommendCode={}", recommendCode);
			resultBase.setResultCode(ResultCode.FAILED.getCode());
		}
		return resultBase;
	}

	@ResponseBody
	@RequestMapping(value = "/getSumOrdersList", method = RequestMethod.GET)
	public ResponseBase<List<Map<String, String>>> getSumOrdersList(
			@RequestParam String recommendCode, String curPage,
			String searchName, String listOrder) {// desc asc
		logger.info(
				"getSumOrdersList入参--recommendCode={},curPage={},searchName={},listOrder={}",
				recommendCode, curPage, searchName, listOrder);
		int pageSize = 20;
		ResponseBase<List<Map<String, String>>> resultBase = new ResponseBase<List<Map<String, String>>>();
		try {
			List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("recommendCode", recommendCode);
			if (StringHelper.isNotEmpty(searchName)) {
				hqlFilter.addSql("and realName like '%" + searchName
						+ "% or productName like '%" + searchName + "% ");
			}
			if ("asc".equals(listOrder)) {
				hqlFilter.addSort("dividend");
				hqlFilter.addOrder("asc");
			} else if ("desc".equals(listOrder)) {
				hqlFilter.addSort("dividend");
				hqlFilter.addOrder("desc");
			} else {
				hqlFilter.addSort("orderCreatedOn");
				hqlFilter.addOrder("desc");
			}
			List<OrderView> orderList = orderViewService.findByFilter(
					hqlFilter, Integer.parseInt(curPage), pageSize);
			if (orderList.size() > 0) {
				for (OrderView view : orderList) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("orderId", "" + view.getOrderId());
					map.put("realName", view.getUserRealName() == null ? ""
							: view.getUserRealName());
					map.put("productName", view.getProductName() == null ? ""
							: view.getProductName());
					map.put("proTerm", "" + view.getProTerm() == null ? ""
							: String.valueOf(view.getProTerm()));
					map.put("orderCreatedOn",
							view.getOrderCreatedOn() == null ? "" : DateUtil
									.transferLongToDate("yyyy-MM-dd",
											view.getOrderCreatedOn()));
					map.put("dividendDate",
							view.getDividendDate() == null ? "" : DateUtil
									.transferLongToDate("yyyy-MM-dd",
											view.getDividendDate()));
					map.put("orderTradeDate",
							view.getOrderTradeDate() == null ? "" : DateUtil
									.transferLongToDate("yyyy-MM-dd",
											view.getOrderTradeDate()));
					map.put("dividend", view.getDividend() == null ? ""
							: String.valueOf(view.getDividend()));
					map.put("successAmount",
							view.getSuccessAmount() == null ? "" : String
									.valueOf(view.getSuccessAmount()));
					map.put("commission", "" + view.getCommissionAmount() + "元");// 佣金规则待定
					resultList.add(map);
				}
			}
			resultBase.setResult(resultList);
			resultBase.setResultCode(ResultCode.SUCC.getCode());
			resultBase.setSize(resultList.size());
		} catch (Exception e) {
			logger.error("理财师：获取订单列表异常！", e);
			logger.info("理财师：获取订单列表异常！recommendCode={}", recommendCode);
			resultBase.setResultCode(ResultCode.FAILED.getCode());
		}
		return resultBase;
	}

	/**
	 * 获取邀请列表
	 * 
	 * @param recommendCode
	 * @param pageNum
	 * @param searchName
	 * @param cardStatus
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getCustomersList", method = RequestMethod.GET)
	// 是否！！！！！！！ 用户表
	public ResponseBase<List<Map<String, String>>> getCustomersList(
			@RequestParam String recommendCode, String pageNum,
			String searchName, String cardStatus) {
		logger.info(
				"getSumCustomersList入参--recommendCode={},pageNum={},searchName={},cardStatus={}",
				recommendCode, pageNum, searchName, cardStatus);
		int pageSize = 20;
		ResponseBase<List<Map<String, String>>> resultBase = new ResponseBase<List<Map<String, String>>>();
		try {
			List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
			HqlFilter userFilter = new HqlFilter();

			if (StringHelper.isNotEmpty(cardStatus)) {// 绑卡用户
				userFilter.addEQFilter("tieCard", Integer.parseInt(cardStatus));
			}
			if (StringHelper.isNotEmpty(searchName)) {
				userFilter.addLKFilter("realName", searchName);
			}
			userFilter.addEQFilter("recommendCode", recommendCode);
			userFilter.addOrder("desc");
			userFilter.addSort("registCts");
			List<SysUser> userList = userService.findByFilter(userFilter,
					Integer.parseInt(pageNum), pageSize);
			if (userList.size() > 0) {
				for (SysUser user : userList) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("registCts",
							user.getRegistCts() == null ? "" : DateUtil
									.transferLongToDate("yyyy-MM-dd",
											user.getRegistCts()));
					map.put("realName",
							user.getRealName() == null ? "" : user
									.getRealName());
					map.put("phone",
							user.getName() == null ? "" : user.getName());
					map.put("encryPhone", user.getEncryptName() == null ? ""
							: user.getEncryptName());
					if (user.getTieCard() == null
							|| CardStatusCode.PAYMENT_DISPLAY_HIDE == user
									.getTieCard()) {
						map.put("tieCard", "否");
					} else {
						map.put("tieCard", "是");
					}
					resultList.add(map);
				}
			}
			resultBase.setResult(resultList);
			resultBase.setResultCode(ResultCode.SUCC.getCode());
			resultBase.setSize(resultList.size());
		} catch (Exception e) {
			logger.error("理财师：获取邀请用户列表异常！", e);
			logger.info("理财师：获取邀请用户列表异常！recommendCode={}", recommendCode);
			resultBase.setResultCode(ResultCode.FAILED.getCode());
		}
		return resultBase;
	}

	@ResponseBody
	@RequestMapping(value = "/getAppointmentsList", method = RequestMethod.GET)
	public ResponseBase<List<Map<String, String>>> getAppointmentsList(
			@RequestParam String recommendCode, String pageNum,
			String searchName, String listOrder) {
		logger.info(
				"getAppointmentsList入参--recommendCode={},pageNum={},searchName={},listOrder={}",
				recommendCode, pageNum, searchName, listOrder);

		int pageSize = 20;
		ResponseBase<List<Map<String, String>>> resultBase = new ResponseBase<List<Map<String, String>>>();
		try {
			List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
			HqlFilter reserveFilter = new HqlFilter();
			if (StringHelper.isNotEmpty(searchName)) {
				reserveFilter.addLKFilter("realName", searchName);
			}
			reserveFilter.addEQFilter("recommendCode", recommendCode);
			if ("desc".equals(listOrder)) {
				reserveFilter.addOrder("desc");
				reserveFilter.addSort("dividend");
			} else if ("asc".equals(listOrder)) {
				reserveFilter.addOrder("asc");
				reserveFilter.addSort("dividend");
			} else {
				reserveFilter.addOrder("desc");
				reserveFilter.addSort("cts");
			}
			List<ReservView> reservList = reservViewService.findByFilter(
					reserveFilter, Integer.parseInt(pageNum), pageSize);
			if (reservList.size() > 0) {
				for (ReservView reserv : reservList) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("realName", reserv.getRealName() == null ? ""
							: reserv.getRealName());
					map.put("productName", reserv.getProductName() == null ? ""
							: reserv.getProductName());
					map.put("cts",
							reserv.getCts() == null ? "" : DateUtil
									.transferLongToDate("yyyy-MM-dd HH:mm:ss",
											reserv.getCts()));
					map.put("reservAmount", reserv.getAmount() == null ? ""
							: (String.valueOf(reserv.getAmount())));
					map.put("proTerm", reserv.getProTerm() == null ? ""
							: (String.valueOf(reserv.getProTerm())));
					map.put("dividend", reserv.getDividend() == null ? ""
							: (String.valueOf(reserv.getDividend())));
					map.put("phone",
							reserv.getPhone() == null ? "" : reserv.getPhone());
					map.put("encryPhone", reserv.getEncryptPhone() == null ? ""
							: reserv.getEncryptPhone());
					resultList.add(map);
				}
			}
			resultBase.setResult(resultList);
			resultBase.setSize(resultList.size());
			resultBase.setResultCode(ResultCode.SUCC.getCode());
		} catch (Exception e) {
			logger.error("理财师：获取预约列表异常！", e);
			logger.info("理财师：获取预约列表异常！recommendCode={}", recommendCode);
			resultBase.setResultCode(ResultCode.FAILED.getCode());
		}
		return resultBase;
	}

}